package com.alog.senior.day22;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/1/25 11:12
 * @Description:
 */
public class TcpServer {
    private static int index = 0;
    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(8888);
        while(true){
            Socket socket = ss.accept();
            new Thread(() -> {
                try {
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\bak" + (++index) + ".png"));
                    BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
//                    OutputStream bos = new FileOutputStream("d:\\bak" + (++index) + ".png");
//                    InputStream bis = socket.getInputStream();
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while((len = bis.read(buf)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bos.close();

                    PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
                    pw.write("Server:已经收到您的文件, 谢谢");
                    pw.flush();

//                    OutputStream out = socket.getOutputStream();
//                    out.write("已经收到, 谢谢".getBytes());
//                    out.flush();

                    socket.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
